#
#   ResourceManager.py
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; version 2 of the License.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   Copyright
#   Author: Nicholas F. Hoover
#   Contributors: Salvatore S. Gionfriddo
#   Created: 2007.06.18
#   Last Modified: 2007.07.19
#

import pygame, os, random
from Options import Options


class ResourceManager(object):
   RANDOM_INDEX = -1

   NUM_SONGS = 3
   (INTRO_SONG,
    GAME_SONG,
    DEAD_SONG) = range(NUM_SONGS)
   
   SONG_NAMES = [
      'intro_song',
      'game_song',
      'dead_song',
      ]


   def __init__(self):
      self.animations = ResourceTable()
      self.sfx = ResourceTable()

      if Options.SOUND['USE_OGG']:
         self.songExtension = '.ogg'
      elif Options.SOUND['USE_MIDI']:
         self.songExtension = '.mid'
      else:
         self.songExtension = ''


   def loadResources(self):
      self.loadAnimations()
      self.loadSFX()

   def getSplashScreen(self):
      return self.loadImage('splashscreen')

   def getMenuSplash(self):
      return self.loadImage('menusplash')

##########
# IMAGES #      
##########

   def loadAnimations(self):
      """
      """
      
      files = os.listdir(os.path.join('data', 'images'))

      for aFile in files[:]:
         if not aFile.endswith('.png'):
            files.remove(aFile)
         elif aFile.rfind('_') != (len(aFile) - 6):
            files.remove(aFile)
         else:
            index = files.index(aFile)
            files[index] = files[index].rstrip('.png')
            
      files.sort()
      
      for aFile in files:
         (name, underscore, frame) = aFile.rpartition('_')
         imageRight = self.loadImage(aFile, -1)
         imageLeft = pygame.transform.flip(imageRight, True, False)
         self.animations.addResource(name + '_Right',imageRight)
         self.animations.addResource(name + '_Left', imageLeft)

         
   def loadImage(self, name, colorkey=None):
      """
      Loads an image from a file in the subdirectory 'data/images'.
      Exits program if image can't be loaded.
       Sets the colorkey (transparent color) as the pure white if colorkey = -1
       """
      fullname = os.path.join('data', 'images', name) + '.png'
      try:
         image = pygame.image.load(fullname)
      except pygame.error, message:
         print 'Cannot load image:', name
         raise SystemExit, message
      image = image.convert()
      
      if colorkey is not None:
         if colorkey is -1:
            colorkey = (255,255,255) #Makes pure white always the transparent color
         image.set_colorkey(colorkey, pygame.RLEACCEL)
            
      return image

   def getAnimationFrames(self, name):
      return self.animations.getResources(name)

   def getImage(self, name, frame):
      return self.animations.getResource(name,frame)
         
                     
##########
# SOUNDS #
##########
   def loadSFX(self):
      """
      Load all .wav files in the data/sounds directory into the sfx ResourceTable.
      """

      files = os.listdir(os.path.join('data', 'sounds'))
      for aFile in files[:]:
         if not aFile.endswith('.wav'):
            files.remove(aFile)
            
      files.sort()

      for aFile in files:
         loadedSound = self.loadSoundFile(aFile)
         loadedSound.set_volume(Options.SOUND['SFX_VOL'])
         (basename, underscore, index) = aFile.rpartition('_')
         self.sfx.addResource(basename, loadedSound)


   def loadSoundFile(self, filename):
      """
      Attempts to load a single sound file from the data/sounds directory named _filename_
      """
      fullname = os.path.join('data','sounds', filename)
      try:
         loadedSound = pygame.mixer.Sound(fullname)
      except pygame.error, message:
         print 'Cannot load sound:', filename, 'from', fullname
         raise SystemExit, message
      return loadedSound
         

   def getSound(self,category, index = RANDOM_INDEX):
      return self.sfx.getResource(category,index)



   def playSound(self, category, index = RANDOM_INDEX):
        sound = self.getSound(category, index)
        if type(sound) == pygame.mixer.Sound:
            sound.play()


   def loadSong(self, song):
      fullname = os.path.join('data', 'sounds', self.SONG_NAMES[song]) + self.songExtension
         
      try:
         pygame.mixer.music.load(fullname)
      except pygame.error, message:
         print 'Cannot load song:', fullname
         raise SystemExit, message
      pygame.mixer.music.set_volume(Options.SOUND['MUSIC_VOL'])



class ResourceTable(object):
   RANDOM_INDEX = -1
    
   def __init__(self):
      self.table = {}
    
   def addCategory(self, category):
      if not self.table.has_key(category):
         self.table[category] = []

   def addResource(self, category, sound):
      if not self.table.has_key(category):
         self.addCategory(category)
      self.table[category].append(sound)

   def getResource(self, category, index = RANDOM_INDEX):
      resource = None
      if self.table.has_key(category):
         categoryElements = self.table[category]
         if len(categoryElements) >= 1:
            if index == ResourceTable.RANDOM_INDEX or index >= len(categoryElements):
               index = random.randrange(len(categoryElements))
                    
               resource = categoryElements[index]

      return resource

   def getResources(self, category):
      resources = None
      if self.table.has_key(category):
         resources = self.table[category]
      return resources
                                 

